package edu.qichen.onlineBlog.framework;

import edu.qichen.onlineBlog.framework.exception.BusinessException;
import edu.qichen.onlineBlog.framework.exception.ErrorCodeEnum;
import lombok.Data;

import java.io.Serial;
import java.io.Serializable;

/**
 * 功能:用于封装服务端返回给前端的数据，包括状态码（code）、消息信息（msg）以及业务数据（data）。
 * 作者:程序员欧阳子韩
 * 日期:2024/3/27 17:14
 */
@Data
public class DataResult<T> implements Serializable {
    @Serial
    private static final long serialVersionUID = 1L;
    private int code; // 响应码
    private String msg; // 响应信息 描述字符串
    private T data; // 响应数据

    public DataResult() {
    }

    public DataResult(int code, T data) {
        this.code = code;
        this.data = data;
    }

    public DataResult(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public DataResult(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public DataResult(String errMsg) {
        this.msg = errMsg;
    }

    public DataResult(int code) {
        this.code = code;
    }

    public static DataResult<Void> success() {
        return new DataResult<>(200,"请求成功");
    }

    public static DataResult<Void> success(int code) {
        return new DataResult<>(code);
    }

    public static DataResult<Void> success(int code, String msg) {
        return new DataResult<>(code,msg);
    }

    public static <T> DataResult<T> success(T data) {
        return new DataResult<>(200, "请求成功", data);
    }

    public static DataResult<Void> fail(ErrorCodeEnum codeEnum) {
        return fail(codeEnum, null);
    }

    public static <T> DataResult<T> fail(ErrorCodeEnum codeEnum, T data) {
        return new DataResult<>(codeEnum.getErrCode(), codeEnum.getErrMsg(), data);
    }

    public static DataResult<Void> fail(BusinessException e) {
        return fail(e.getErrCode(), e.getErrMsg());
    }

    public static DataResult<Void> fail(String errMsg) {
        return new DataResult<>(errMsg);
    }

    public static DataResult<Void> fail(int errCode, String errMsg) {
        return new DataResult<>(errCode, errMsg, null);
    }

    public static boolean isSuccess(DataResult<?> dataResult) {
        return dataResult.code == 200;
    }

    public DataResult<T> setData(T data) {
        this.data = data;
        return this;
    }
}
